import socket
import sys
import os
import time
import math
import asyncio
import threading
import random
from function.tools import autobcc, LoadConf, int_to_hex, str_to_hex, getRealTimeHex, get_weizhi,logger, log, conf
# import recvData

from vehicle import Alarm


iovConf = conf.loadConfIni('iovConf')
tspConf = conf.loadConfIni('tspConf')

class Tcp():
    tcpInfo = tspConf.host_info
    title = '车辆网tbox测试'
    # hostname = 'tbox-clitest.molichuxing.com'
    # hostname = 'tbox-cli.molichuxing.com'
    hostname: str = tspConf.get(tcpInfo)

    port: int = int(tspConf.port)
    timeout: int = 30
    # 超时
    socket.setdefaulttimeout(timeout)
    # socket.setblocking(0)
    # 设置地址
    recvLen: int = 2048
    def create_connect(self):
        
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 第二步：建立连接
        logger.debug(f'创建连接成功:{self.hostname},{self.port}')
        self.s.connect((self.hostname, self.port))
        logger.info('开启新线程 接收返回值')
        self.t = threading.Thread(target= self.get_recv, args=(self.recvLen,))
        self.t.setDaemon(True)#设置为后台线程，这里默认是False，设置为True之后则主线程不用等待子线程
        self.t.start()#开启线程
        # self.s.setblocking(0)
        return self.s

    # def send_and_recv(self, data):
        #返回变成异步获取, 此方法废弃
    #     _recv = self.send_data(data)
    #     logger.debug(f'二进制消息发送成功:{data}')
    #     logger.debug(f'返回二进制消息为:{ self.recv}')
    #     return _recv
    def get_recv(self, _len):
        
        logger.debug('新线程开启成功')
        while True:
            # 循环获取返回值
            try:
                _recv = self.s.recv(_len)
            except Exception as e:
                logger.info(e)
                # self.t = ''
                self.get_recv(_len)
                return
            else:
                if _recv: logger.debug(f'16进制消息接收[下行]:{_recv}')

    def send_data(self, data,):
        # self.s = self.create_connect()
        if self.t:
            logger.debug('接收线程已存在,不启动线程')
        else:
            self.t = threading.Thread(target= self.get_recv, args=(self.recvLen,))
        # t.setDaemon(True)#设置为后台线程，这里默认是False，设置为True之后则主线程不用等待子线程
            self.t.start()#开启线程

        data = data.replace(' ', '').replace('\n', '').replace('\t', '')
        # logger.info('入参',data,'\n','*'*20)
        data = autobcc(data)
        
        # logger.info('校验',data,'--------\n','*'*20)

        self.s.send(bytes.fromhex(data))
        logger.debug(f'16进制消息发送[上行]:{data}')
        
        # logger.info(self.s.recv(2048))
        # recv = self.s.recv(2048)
        # self.recv_data()


class Tsp(Tcp):

    # logger.info(iovConf.a,'=======================')
# TCP连接
    # vin: str = '4C4E425343423346314A57313739303136'
    # vin: str = '4c4e425343423346304a57313736323834'
    vin: str = 'LNBSCB3F0JW176284'
    # vin: str = 'MOLICB3F9JW100142'
    # vin: str = 'MOLICB3F9JW100054'
    # vin = str_to_hex(vin)

    # iccId: str = '3839383630324234303731363330303037323839'
    iccId: str = '898602B4071630002173'
    # iccId: str = '63333373434353533363'
    # iccId = str_to_hex(iccId)

    # devicesId: str = '36383835303738'
    devicesId: str = '6870404'
    # devicesId: str = '3533363'
    # devicesId = str_to_hex(devicesId)
    # 里程
    # mileage: str = '000001D6'
    mileage: float = 3120.1
    # nowTime: str = '12060C0E0A07'
    nowTime: list = [19, 6, 12, 14, 10, 7]
    nowTime = '19-06-12 14:10:07'.replace('.', '-').replace(
        ' ', '-').replace(':', '-').split('-')
    nowTime = [int(x) for x in nowTime]
    # nowTime = ''.join(int_to_hex(x,2) for x in nowTime)
    nowTime = getRealTimeHex() 
    # Latitude , Longitude = 39.9140831518,116.4079933746 #天安门东
    # Latitude, Longitude = 39.913289, 116.380625  # 西单
    Longitude: str = tspConf.longitude   # 西单
    Latitude: str = tspConf.latitude

    speed: float = float(tspConf.speed)

    # mileage = int_to_hex(mileage*10)

    # 总电压
    # countVoltage: str = '0C8C'
    countVoltage: float = 12
    # 档位
    gears = '1101'
    # countVoltage *= 10
    # countVoltage = int_to_hex(int(countVoltage),4)
    # 蓄电池电压
    batteryVoltage: float = 9.9
    # 总电流
    # countElectricity: str = '2710'
    countElectricity: float = 1
    # countElectricity = int_to_hex(countElectricity,4)
    # 绝缘电阻
    resistor = 500

    # SOC
    # SOC = '44'
    SOC: float = 14
    # SOC = int_to_hex(SOC,2)

    # 报警等级
    # alarmBool = 0
    # alarmBool = int_to_hex(alarmBool,2)
    alarmLevel: int = 1
    # alarmLevel = int_to_hex(alarmLevel,2)
    # 报警类型
    alarmValue: str =  iovConf.alarm_value
    # 中控锁状态
    centerBlock: int = 1  # 上锁，解锁，无效 【0,1,255】“0xFE”表示异常，“0xFF”表示无效
    # 手刹状态
    #gps里程
    GpsMileage = 2800
    # logger.info()
    realTimes = 0
    dataflag = ''
    def __init__(self):
        
        self.mileageHex = int_to_hex(int(self.mileage*10))

        self.vinHex = str_to_hex(self.vin)

        self.iccIdHex = str_to_hex(self.iccId)
        self.devicesIdHex = str_to_hex(self.devicesId)
        # self.nowTimeHex = ''.join(int_to_hex(x,2) for x in self.nowTime)##固定当前时间
        self.nowTimeHex = getRealTimeHex()  # 动态获取时间
        self.LongitudeHex, self.LatitudeHex = get_weizhi(
            f'{self.Longitude},{self.Latitude}')   #local_Longitude_str, local_latitude_str
        self.countVoltageHex = int_to_hex(int(self.countVoltage*10), 4)
        self.batteryVoltageHex = int_to_hex(int(self.batteryVoltage*10), 2)
        self.countElectricityHex = int_to_hex(
            self.countElectricity*10+10000, 4)
        self.SOCHex = int_to_hex(self.SOC, 2)
        self.alarmLevelHex = int_to_hex(self.alarmLevel, 2)
        # self.alarmValueHex = self.alarm(self.alarmValue)
        self.alarmValueHex = self.alarmValue
        self.centerBlockHex = int_to_hex(self.centerBlock, 2)
        self.GpsMileageHex = int_to_hex(self.GpsMileage, 8)
        # logger.info(self.alarmLevel,'当前报 级')
        # logger.info(self.alarmValue,'当前报警字段')

        self.regeditData = f'''
    2323DBFE {self.vinHex} 010035 {self.nowTimeHex} 0001 {self.vinHex} {self.iccIdHex} 07 {self.devicesIdHex}   
    '''
        self.loginData = f'''
    232301FE{self.vinHex}01002A{self.nowTimeHex}0013{self.iccIdHex}010C313138323133333035353031
    '''
        self.realData = f'''
    232302FE {self.vinHex} 010179{self.nowTimeHex}01010301012D {self.mileageHex} {self.countVoltageHex} {self.countElectricityHex} 
    {self.SOCHex} 012e
    27100900020101015657204EAA480C8A27100500 {self.LongitudeHex} {self.LatitudeHex} 0601080F0001290ED801013C01063B07
     {self.alarmLevelHex}
     {self.alarmValueHex} 
     000000000801010C8C271000540001540EEC0EEC0EEC0EEC0EEC0EEC0EEC0F000
    EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0EEC0F000F000F000EEC0F000F000F000F000F000EEC0F000F000EEC0EEC0EEC0EEC0ED80EEC0ED80ED80ED80ED80EEC0ED80EEC0F000F000EEC0EEC0F000EEC0F000EEC0F000EEC0EEC0F000F000F000F000F000F000F000F000F000F000F000F000EEC0EEC0EEC0ED80EEC0EEC0EEC0EEC0EEC0EEC0EEC0ED8090101000E3C3C3C3C3C3B3B3B3C3B3C3C3C3C
    A000630002010014021D0000  {self.centerBlockHex} 0001 {self.batteryVoltageHex} 0001 {self.GpsMileageHex} 001E0162121F0200470705C0AA5091962894FC5405C1240302B33EB2043705C25E502710444304CB05C3000000002301062C05C4059B0BC70000002F05C5004001540E18352405C60448002200000000
    '''
        # def __init__(self):
        #local_x, local_y = map(int_to_hex,get_weizhi(input('39.9150378092,116.4039915188')))
        #local_x, local_y = map(int_to_hex,get_weizhi(input('39.9150378092,116.4039915188')))

        # self.s = self.Tcp()
        # def Tcp(self):
        #hostname = 'tbox-clitest.molichuxing.com'

        # logger.info('参数初始化完成')
        # s.send(bytes.fromhex(baowen1))
        # 第三步：接收数据
        # recv = s.recv(1024)
        # logger.info('tcp已连接')
        # #logger.info(recv)
        
    def setAttr(self, attr, value):
        setattr(self, attr, value)
        logger.info(f'{self.vin}:设置后的{attr}={value}')
        # self.__init__()
        # logger.info(getattr(self,attr))
    def send_data(self,*arg):
        self.realTimes += 1
        try:
            super().send_data(*arg)
        except Exception:
            logger.exception(sys.exc_info())
            raise
        logger.info(f'第{self.realTimes}次发送数据{self.dataflag}')
    def getAttr(self, attr):
        # logger.info(self.Longitude,'========================================4====================')
        self.__init__()
        logger.info(f'\nVIN:{self.vin}\tDEVICESID:{self.devicesId}\tICCID:{self.iccId},baidu09{(self.Latitude, self.Longitude)}')
        # logger.info(self.Longitude,'---------------------------------------3--------------------------')
        # time.sleep(10000)
        # logger.info('vin:',self.vin)
        # logger.info('iccId:',self.iccId)
        # logger.info('devicesId:',self.devicesId)
        # logger.info('mileage:',self.mileage)
        # logger.info('nowTime:',self.nowTime)
        # logger.info('Longitude:',self.Longitude)
        # logger.info('Latitude:',self.Latitude)
        # logger.info('alarmLevel:',self.alarmLevel)
        # logger.info('alarmValue:',self.alarmValue)
        # logger.info(self.)
        # logger.info(getattr(self,attr))
        
        if self.dataflag != attr:
            self.realTimes=0
        self.dataflag = attr
        return getattr(self, attr).replace(' ', '').replace('\n', '').replace('\t', '').strip()
        # pass

    def setAlarm(self, alarmList: list) -> str:
        '''
1.温度差异报警\t2.电池高温报警\t3.车载储能装置类型过压报警\t4.车载储能装置类型欠压报警\t5.SOC低报警
6.单体电池过压报警\t7.单体电池欠压报警\t8.SOC过高报警\t9.SOC跳变报警\t10.可充电储能系统不匹配报警
11.电池单体一致性差报警\t12.绝缘报警\t13.DC-DC温度报警\t14.制动系统报警\t15.DC-DC状态报警\t16.驱动电机控制器温度报警
17.高压互锁状态报警\t18.驱动电机温度报警\t19.车载储能装置类型过充\n'
'''
        # 默认报警列表、、不报警
        # logger.info(alarmList)
        # alarmDefaultList = [0 for x in range(32)]
        # if alarmDefaultList:
        # for i in alarmList:
        # alarmDefaultList[i] = 1

        # return alarmDefaultList
    def alarm(self, type):
        #alarmsign = '{:032b}'.format(int(math.pow(2, int(type)-1)),'b')
        alarmsign = '{:0>8x}'.format(int((math.pow(2, int(type) - 1))))
        return ''.join(alarmsign)

    def send_register_data(self, **kwags): pass
    #self.register = '2323DBFE'+vinhex(self.vin)+'010035120B150E2D0A0001'+vinhex(self.vin)+self.iccId+'07'+self.devices_id

    def send_login_data(self): pass

    def send_real_data(self):
        self.local_x, self.local_y = map(
            int_to_hex, get_weizhi('39.9150378092,116.[[[[[[[[[[[[[[[[[[[[[4039915188]]]]]]]]]]]]]]]]]]]]]'))


if __name__ == '__main__':
    conf = LoadConf('conf.ini')
    iovconf = conf.loadConfIni('iovConf')
    logger.info(iovconf)
    tsp = Tsp()
    tsp.create_connect()
    # logger.info(loadConf('iovConf','alarmValue'))
    # time.sleep(1000)
    # tsp = Tsp()
    # tsp.alarmValue
    # time.sleep(10000)
    # pass
    # main('testInputtRegList')
    # main('testInputDefault')
    # main('testLoopSend')
